package com.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class UIMakerHttpClinet {
	private static final Map<String, Object> param = new HashMap<String, Object>();
	private static final Map<Integer, String> shefeng = new HashMap<Integer, String>();
	
	public static void main(String[] args) throws UnsupportedEncodingException {
		//String url = "http://www.uimaker.com/member/reg_new.php?fromid=86858";
		
		//==================================================//
		String url = "http://www.uimaker.com/member/reg_new.php";
		init();
		String body = doPost(url, param, "gb2312");
		System.out.println(body);
		printBody(body);
	}
	
	
	private static String[] builCity(){
		String[][] citys = {
			{"西城区","朝阳区","海淀区","丰台区"},//北京
			{"河东区","河西区","东丽区","南开区"},//天津
			{"徐汇区","虹口区","嘉定区","长宁区"},//上海
			{"广州","深圳","佛山","珠海"},//广东
		};
		int random=(int)(Math.random()*10);
		int sfIdx = random%4;
		random=(int)(Math.random()*10);
		int ctIdx = random%4;
		String[] c = new String[2];
		c[0] = shefeng.get(sfIdx);
		c[1] = citys[sfIdx][ctIdx];
		return c;
	}
	
	private static void init(){
		shefeng.put(0, "北京");
		shefeng.put(1, "天津");
		shefeng.put(2, "上海");
		shefeng.put(3, "广东");
		
		String uname = buildUname();
		param.put("uname", uname);
		param.put("userid", uname);
		String pwsd = buildPwd();
		param.put("userpwd", pwsd);
		param.put("userpwdok", pwsd);
		param.put("email", buildQQEmail());
		param.put("sex", buildSex());
		String[] citys = builCity();
		param.put("sheng", citys[0]);
		param.put("shi", citys[1]);
		param.put("mtype", "个人");//个人
		param.put("zhiye", "UI设计师");//职业UI设计师
		
		param.put("agree", "");
		param.put("vdcode", "");
		param.put("comefrom", "");
		param.put("fromuser", "");
		
		param.put("step", "1");
		param.put("dopost", "regbase");
		param.put("fromid", "86858");
	}
	
	private static void printBody(String body){
		boolean msg = isAllMatch(body, ".*您今天已经注册过了一个用户.*");
		String title = match(body, "<title>(.*?)</title")[1];
		if (msg) {
			System.out.println(title+"---您今天已经注册过了一个用户，如需继续注册，请隔日再来");
		}else{
			System.out.println(title);
		}
	}
	
	private static String buildUname(){
		String uname = getUUID();
		return uname.substring(6, 16);
	}
	
	private static String buildPwd(){
		String pwsd = getUUID();
		return pwsd.substring(6, 12);
	}
	
	private static String buildQQEmail(){
		int random=(int)(Math.random()*1000000000); 
		return random+"@qq.com";
	}
	
	private static String buildSex(){
		int random=(int)(Math.random()*10);
		return random>5 ? "男" : "女";
	}
	
	 /**
     * <pre>
     * 发送带参数的POST的HTTP请求
     * </pre>
     * @param reqUrl HTTP请求URL
     * @param parameters 参数映射表
     * @return HTTP响应的字符串
     */
    public static String doPost(String reqUrl, Map<String, Object> parameters, String recvEncoding){
    	System.out.println("发送请求："+reqUrl+"......");
        HttpURLConnection url_con = null;
        String responseContent = null;
        try{
            StringBuffer params = new StringBuffer();
            for (Iterator<Entry<String, Object>> iter = parameters.entrySet().iterator(); iter.hasNext();){
                Entry<String, Object> element = iter.next();
                params.append(element.getKey());
                params.append("=");
                params.append(URLEncoder.encode(element.getValue().toString(), recvEncoding));
                //params.append(element.getValue().toString());
                params.append("&");
            }

			if (params.length() > 0) {
				params = params.deleteCharAt(params.length() - 1);
			}

            URL url = new URL(reqUrl);
            url_con = (HttpURLConnection) url.openConnection();
            url_con.setRequestProperty("Host", "www.uimaker.com");
            url_con.setRequestProperty("Referer", "http://www.uimaker.com/member/reg_new.php?fromid=86858");
            //Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36
            url_con.setRequestProperty("User-Agent", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)");
            url_con.setRequestMethod("POST");
            //System.setProperty("sun.net.client.defaultConnectTimeout", "5000");// （单位：毫秒）jdk1.4换成这个,连接超时
            //System.setProperty("sun.net.client.defaultReadTimeout", "10000"); // （单位：毫秒）jdk1.4换成这个,读操作超时
            url_con.setConnectTimeout(5000);//（单位：毫秒）jdk
            url_con.setReadTimeout(5000);//（单位：毫秒）jdk 1.5换成这个,读操作超时
            url_con.setDoOutput(true);
            
            byte[] b = params.toString().getBytes();
            url_con.getOutputStream().write(b, 0, b.length);
            url_con.getOutputStream().flush();
            url_con.getOutputStream().close();

            InputStream in = url_con.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(in,recvEncoding));
            String tempLine = rd.readLine();
            StringBuffer tempStr = new StringBuffer();
            String crlf= System.getProperty("line.separator");
            while (tempLine != null){
                tempStr.append(tempLine);
                tempStr.append(crlf);
                tempLine = rd.readLine();
            }
            responseContent = tempStr.toString();
            rd.close();
            in.close();
        }
        catch (IOException e){
            System.out.println("网络故障"+e.getMessage());
        }
        finally{
			if (url_con != null) {
				url_con.disconnect();
			}
        }
        return responseContent;
    }
    
    public static boolean isAllMatch(String s, String pattern) {
		Matcher m = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE).matcher(s);
		while (m.find()) {
			return true;
		}
		return false;
	}
    
    public static String[] match(String s, String pattern) {
		Matcher m = Pattern.compile(pattern).matcher(s);

		while (m.find()) {
			int n = m.groupCount();
			String[] ss = new String[n + 1];
			for (int i = 0; i <= n; i++) {
				ss[i] = m.group(i);
			}
			return ss;
		}
		return null;
	}
    
	public static String getUUID() {
		String uuid = UUID.randomUUID().toString();
		return uuid.substring(0, 8) + uuid.substring(9, 13) + uuid.substring(14, 18) + uuid.substring(19, 23) + uuid.substring(24);
	}
}
